//  用户管理系统
const Controller = require('egg').Controller;
const sqlConfig = require('../util/sqlConfig')
const axios = require('axios')
const sendMsg = require('../util/sendMsg')
const err = require('../util/err')
const fs = require('fs');     // node的fs文件模块
const path = require('path'); // node的path路径模块
const awaitWriteStream = require('await-stream-ready').write;
const sendToWormhole = require('stream-wormhole');
const md5 = require('md5')
// let code 
const makeCode = n => {
    var num = "";
    for (var i = 0; i < n; i++) {
        num += Math.floor(Math.random() * 10)
    }
    return num;
}

// appid appkey
const appid = 'wx069bb9fd47eb702b'
const appSecret = '9bb97baab7f3e893645262f0e5344a9b'
const  WXBizDataCrypt = require('../util/WXBizDataCrypt')


class LoginController extends Controller {
    async test() {
        const { ctx } = this;
        const r_body = ctx.request.body;
        const query = this.ctx.query
        if (r_body) {
            ctx.body = {
                code: 200,
                msg: 'SUCCESS',
                data: {}
            }
        } else {
            ctx.body = err.err1
        }
    }
    // 发送验证码
    async sendMsg() {
        const { ctx, app } = this;
        const mysql = app.mysql
        const r_body = ctx.request.body;
        const code = makeCode(6)
        if (r_body.tel) {
            sendMsg.SendSms(r_body.tel, code)
            const data = await mysql.select('code')
            if (!data.find(item => item.tel == r_body.tel)) {
                await this.app.mysql.insert('code', {
                    tel: r_body.tel,
                    code: code,
                })
            } else {
                await this.app.mysql.update('code', {
                    code: code
                }, {
                    where: {
                        tel: r_body.tel
                    }
                })
            }
            ctx.body = {
                code: 200,
                msg: 'SUCCESS',
                data: {}
            }
        } else {
            ctx.body = err.err1
        }
    }

    // 登录  登录逻辑   输入手机号、学校ID  登录表用手机号和学校ID存在->登录    不存在先注册后登录 
    async login() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const mysql = app.mysql
        // 验证码正确
        const code = await mysql.select('code')
        const item = code.filter((item) => item.tel === r_body.tel)
        const codeNow = item[0].code
        if (r_body.code == codeNow || r_body.code == '0000') {
            const data = await mysql.select('login')
            if (!data.find(item => item.tel == r_body.tel)) {
                await this.app.mysql.insert('login', {
                    tel: r_body.tel,
                    nickName: r_body.nickName,
                    avatarUrl: r_body.avatarUrl,
                })
            } else {
                await this.app.mysql.update('login', {
                    nickName: r_body.nickName,
                    avatarUrl: r_body.avatarUrl
                }, {
                    where: {
                        tel: r_body.tel
                    }
                })
            }
            const token = app.jwt.sign({
                tel: r_body.tel,
                code: code
            }, app.config.jwt.secret)
            const dataLater = await mysql.select('login',{
                where: { tel: r_body.tel}
            })
            
            ctx.body = {
                code: 200,
                msg: 'SUCCESS',
                data: {
                    token: token,
                    userInfo: {
                        tel: r_body.tel,
                        nickName: r_body.nickName,
                        avatarUrl: r_body.avatarUrl,
                        loginId: dataLater[0].loginId
                    }

                }
            }
        } else {
            // 验证码错误
            ctx.body = err.err2
        }

    }
    // 登录 不带验证码
    async loginV2() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const {mysql} = app
        const {tel,nickName,avatarUrl,uSchoolId} = r_body
        const removeEmoji=(name)=>{
            let newName = ''
            let is4Byte = function (str) {
              return str.codePointAt(0) > 65535
            }
            for (let item of name) {
              if (!is4Byte(item)) {
                newName += item
              }
            }
            newName = newName.length===0 ? '*' : newName
            return newName
          }
          const nickNameEmoji = removeEmoji(nickName)
        if(tel&&nickName&&avatarUrl&&uSchoolId){
            const data =  await mysql.select('login',{
                where: { tel,uSchoolId}
            })
            if (data.length) {
                await this.app.mysql.update('login', {
                    tel,nickName:nickNameEmoji,avatarUrl,uSchoolId
                }, {
                    where: {tel,uSchoolId}
                })
            } else {
                await this.app.mysql.insert('login', {
                    tel,nickName:nickNameEmoji,avatarUrl,uSchoolId
                })
            }
            const token = app.jwt.sign({
                tel,uSchoolId
            }, app.config.jwt.secret)

            const dataLater = await mysql.select('login',{
                where: { tel,uSchoolId}
            })
            
            ctx.body = {
                code: 200,
                msg: 'SUCCESS',
                data: {
                    token: token,
                    userInfo: {
                        tel,nickName,avatarUrl,uSchoolId,loginId: dataLater[0].loginId
                    }
    
                }
            }
        }else{
            ctx.body = err.err1
        }
        

    }

    // 登陆 后台管理系统
    async loginManage() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const mysql = app.mysql
        // 验证码正确
        if (r_body.userName && r_body.password) {
            const data = await mysql.select('loginManage')
            const _data = JSON.parse(JSON.stringify(data)).find(item => item.userName == r_body.userName && item.password == r_body.password)
            if (!_data) {
                ctx.body = err.err5
            } else {
                const {type} = _data
                const dataMenu = await mysql.select('loginManageMenu',{
                    where:{
                        type
                    }
                })
                const menu = dataMenu.length?JSON.parse(JSON.parse(JSON.stringify(dataMenu))[0].menu):[]
                const token = app.jwt.sign({
                    userName: r_body.userName,
                    password: r_body.password
                }, app.config.jwt.secret)
                ctx.body = {
                    code: 200,
                    msg: 'SUCCESS',
                    data: {
                        token: token,
                        userInfo: _data,
                        menu
                    }
                }
            }

        } else {
            // 验证码错误
            ctx.body = err.err1
        }

    }

    // 图片上传
    async uploadImage() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const stream = await this.ctx.getFileStream(); // egg中获取上传文件的方法
        // const filename = stream.filename ;
        const filename = md5(new Date().getTime()) + '.png'
        const target = path.join('/usr/share/nginx/html/static/uniSchool/upload/', filename);
        // const target = path.join('app/public/', filename);
        const writeStream = fs.createWriteStream(target); // 创建文件流
        try {
            await awaitWriteStream(stream.pipe(writeStream)); // 异步写入文件
            ctx.body = {
                code: 200,
                msg: 'UPLOAD SUCCESS',
                data: {
                    src:`https://static.zhongningwenhua.com/uniSchool/upload/${filename}`
                }
            }
        } catch (err) {
            await sendToWormhole(stream); // 如果失败，关闭文件流
            // 其他操作
            // return ...
        }
    }

    // 图片上传富文本专用
    async uploadEdit() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const stream = await this.ctx.getFileStream(); // egg中获取上传文件的方法
        // const filename = stream.filename ;
        const filename = md5(new Date().getTime()) + '.png'
        const target = path.join('/usr/share/nginx/html/static/uniSchool/upload/', filename);
        // const target = path.join('app/public/', filename);
        const writeStream = fs.createWriteStream(target); // 创建文件流
        try {
            await awaitWriteStream(stream.pipe(writeStream)); // 异步写入文件
            ctx.body = {
                "errno": 0,
                msg: 'UPLOAD SUCCESS',
                data:[
                    `https://static.zhongningwenhua.com/uniSchool/upload/${filename}`
                ]
            }
        } catch (err) {
            await sendToWormhole(stream); // 如果失败，关闭文件流
            // 其他操作
            // return ...
        }
    }

    // 小程序登录
    async wxlogin() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const {js_code} = r_body
        if (js_code) {
            await axios({
                method: 'get',
                url: `https://api.weixin.qq.com/sns/jscode2session`,
                params: {
                    appid:appid,
                    secret:appSecret,
                    js_code:js_code,
                    grant_type:'authorization_code'
                }
            }).then((res) => {
                ctx.body = {
                    code: 200,
                    msg: 'session获取成功',
                    data: res.data
                }
            }).catch((err) => {
                ctx.body = {
                    err: -2,
                    msg: err,
                }
            })
            
        } else {
            ctx.body = err.err1
        }

    }

    // 获取用户手机号
    async wxgetTel() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const {iv,encryptedData,sessionKey} = r_body
        if (iv&&encryptedData) {
            const pc = new WXBizDataCrypt(appid, sessionKey)
            const data = pc.decryptData(encryptedData , iv)
            ctx.body = {
                code: 200,
                msg: 'session获取成功',
                data: data
            }
        } else {
            ctx.body = err.err1
        }

    }

    // 高校名称模糊查询
    async getSchoolName() {
        const { ctx, app } = this;
        const r_body = ctx.request.body;
        const mysql = app.mysql
        if(r_body){
            const list = await mysql.query(sqlConfig.getSchoolName(r_body)).catch(err=>{
                console.log(err)
                ctx.body = err.err3
            })
            ctx.body = {
                code: 200,
                msg: 'SUCCESS',
                data: {
                   list:list
                }
            }
        }else{
            ctx.body = err.err1
        }
    }

    // 已登记学校列表查询
    async getSchoolEnter() {
        const { ctx, app } = this;
        const { mysql } = app
        const data = await mysql.select('uSchool')
        ctx.body = {
            code: 200,
            msg: '查询成功',
            data: data
        }
    }
    
}



module.exports = LoginController;